﻿using System.Text;

namespace PmSoft.Core.Extensions;

public static class ByteExtensions
{
	/// <summary>
	/// 将字节数组转换为字符串
	/// </summary>
	/// <param name="v">字节数组</param>
	/// <param name="charSet">字符集，默认为 "utf-8"</param>
	/// <returns>转换后的字符串</returns>
	public static string ToStr(this byte[] v, string charSet = "utf-8")
	{
		try
		{
			return Encoding.GetEncoding(charSet).GetString(v);
		}
		catch
		{
			// 如果指定的字符集无效，则使用 UTF-8 编码
			return Encoding.UTF8.GetString(v);
		}
	}

	/// <summary>
	/// 将字节数组转换为 Base64 字符串
	/// </summary>
	/// <param name="bytes">字节数组</param>
	/// <returns>Base64 字符串</returns>
	public static string ToBase64(this byte[] bytes)
	{
		return Convert.ToBase64String(bytes);
	}

	/// <summary>
	/// 将字节数组转换为十六进制字符串
	/// </summary>
	/// <param name="bytes">字节数组</param>
	/// <returns>十六进制字符串</returns>
	public static string ToHex(this byte[] bytes)
	{
		return BitConverter.ToString(bytes, 0, bytes.Length).Replace("-", "");
	}
}
